from flask import Flask, render_template, jsonify, request
import threading
import redis
# from flask_cors import CORS
import time
import json
import os
app = Flask(__name__)


# 打开文件并读取JSON数据
keyDic = {}
script_directory = os.path.dirname(__file__)

with open( script_directory + '/config.json', 'r') as f:
    keyDic = json.load(f)

# 定义一个简单的键值对字典，用于在页面上显示
key_value_pairs = {
    'name': 'Alice',
    'age': 30,
    'city': 'New York',
    'country': 'USA'
}
ip = "127.0.0.1"
key1_comment = []
key2_comment = []
key3_comment = []
def update_data():
    # 连接到 Redis 数据库
    try:
        r = redis.Redis(host=ip, port=6379, db=0, socket_connect_timeout=5)
    except TimeoutError as e:
       print("timeout:", e)
       return
 
    # 获取所有键值对
    # all_keys = r.keys('*')
    all_keys = [key.decode('utf-8') for key in r.keys('*')]

    # 将所有键值对分成三列
    num_keys = len(all_keys)
    num_per_column = (num_keys + 2) // 3  # 向上取整，保证每列数量尽可能平均
    keys1 = all_keys[:num_per_column]
    keys2 = all_keys[num_per_column:num_per_column*2]
    keys3 = all_keys[num_per_column*2:]
    # 根据键获取对应的值
    values1 = [r.get(key).decode('utf-8') for key in keys1]
    values2 = [r.get(key).decode('utf-8') for key in keys2]
    values3 = [r.get(key).decode('utf-8') for key in keys3]
    key1_comment.clear()
    key2_comment.clear()
    key3_comment.clear()

    for key in keys1:
        if key in keyDic.keys():
            key1_comment.append(keyDic[key])
        else:
            key1_comment.append(key)

            
            
    for key in keys2:
        if key in keyDic.keys():
            key2_comment.append(keyDic[key])
        else:
            key2_comment.append(key)


    for key in keys3:
        if key in keyDic.keys():
            key3_comment.append(keyDic[key])
        else:
            key3_comment.append(key)

    # 将键值对存储为字典，以便渲染模板
    table1 = dict(zip(key1_comment, values1))
    table2 = dict(zip(key2_comment, values2))
    table3 = dict(zip(key3_comment, values3))
    
    return table1, table2, table3


def update_tables():
    while True:
        # 每秒钟更新一次数据
        time.sleep(1)

        # 更新示例数据
        # 这里假设您有一个更新数据的函数 update_data()，它会返回新的数据字典
        new_table1, new_table2, new_table3 = update_data()

        # 更新全局变量
        global table1, table2, table3
        table1 = new_table1
        table2 = new_table2
        table3 = new_table3

# 在 Flask 应用启动时启动定时器线程
# update_thread = threading.Thread(target=update_tables)
# update_thread.daemon = True
# update_thread.start()



@app.route('/')
def index():
    return render_template('index.html')


@app.route('/set_ip', methods=['POST'])
def set_ip():
    # 在此处调用 gotip 方法，并传递 IP 参数
    json_data = request.get_json()
    data = jsonify(json_data)
    ip_address = json_data.get('ip')

    global ip 
    ip = request.json['ip']  # 获取前端发送过来的 IP
    print("Setting IP %s" % ip)
    return jsonify({'message': 'IP 设置成功'})


@app.route('/send_cmd', methods=['POST'])
def send_cmd():
    # 在此处调用 send cmd 方法，并传递 IP 参数
    cmd = request.json['cmd']  # 获取前端发送过来的 IP
    print("got cmd %s" % cmd)

    try:
        r = redis.Redis(host=ip, port=6379, db=0, socket_connect_timeout=5)
    except TimeoutError as e:
       print("timeout:", e)
       return
    hexbytes = bytearray.fromhex(cmd)
    r.publish("aiCommand", hexbytes.decode('utf8'))
    return jsonify({'message': '指令发送成功'}) 

@app.route('/get_ip')
def get_ip():
    global ip
    return jsonify(ip)


@app.route('/get_table_data')
def get_table_data():
    table_data = update_data()
    return jsonify(table_data)


if __name__ == '__main__':
    app.run(host = '0.0.0.0', port = 60000,debug=True)